package com.haixiaoke.saas.system.controller.system;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.saas.common.config.OrgStructureConfig;
import com.haixiaoke.saas.common.constant.Constants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysMenu;
import com.haixiaoke.saas.common.core.domain.entity.SysUser;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.SysLoginService;
import com.haixiaoke.saas.system.framework.web.service.SysPermissionService;
import com.haixiaoke.saas.system.service.ISysMenuService;
import com.haixiaoke.saas.user.domain.OrgUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author haixiaoke
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private OrgStructureConfig orgStructureConfig;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        JSONObject jsonObject = orgStructureConfig.getToken(loginBody.getPhone(), loginBody.getPassword());
        /*if (StrUtil.isNotBlank(msg)) {
            return AjaxResult.error(msg);
        }*/

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(jsonObject, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        OrgUser user = SecurityUtils.getLoginUser().getOrgUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(null);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(null);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
